package com.habdqn.studentmanager.util;

import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.github.pagehelper.PageInfo;
import com.habdqn.studentmanager.bean.AttendanceMachine;
import com.habdqn.studentmanager.service.AttendanceService;

/**
 * @author Fan
 * 
 *         2017年7月4日
 * 
 */
@Component
public class AttendanceConnectionManager {

	@Resource
	private AttendanceService attService;

	private static AttendanceConnectionManager instance = null;
	
	private static Map<Integer, AttendanceConnection> connections = new Hashtable<>();

	/**
	 * 初始化
	 */
	@PostConstruct
	public void init() {
		
		if (null == instance) {
			instance = this;
		}
		
		PageInfo<AttendanceMachine> pageInfo = attService.findMachineList(null, null);
		if (null == pageInfo || pageInfo.getList() == null) {
			return;
		}
		
		List<AttendanceMachine> machines = pageInfo.getList();
		for (AttendanceMachine machine : machines) {
			add(machine);
		}
	}
	
	/**
	 * 加入到内存中，并开始与考勤机连接
	 * @param machine
	 */
	public static void add(AttendanceMachine machine) {
		AttendanceConnection connection = new AttendanceConnection(machine, instance.attService);
		connection.start();
		connections.put(machine.getId(), connection);
	}
	
	/**
	 * 从内存中移除，并停止与考勤机的连接
	 * @param machineId 考勤机编号
	 * @return
	 */
	public static AttendanceConnection remove(Integer machineId) {
		AttendanceConnection connection = connections.remove(machineId);
		connection.interrupt();
		return connection;
	}
	
	/**
	 * 获取对应的连接, 可用于查看连接状态
	 * @param machine
	 * @return
	 */
	public static AttendanceConnection get(AttendanceMachine machine) {
		return connections.get(machine.getId());
	}
}
